<?php

namespace App\Library\AliYun\AliYunCloud;

use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Exception;

class AliYunCloudApi extends BaseAliYunCloudApi
{
    private Sts $client;

    public function __construct()
    {
        parent::__construct();
        $this->client = $this->createClient();
    }

    /**
     * @return array
     */
    public function getTemporaryVouchers(): array
    {
        $assumeRoleRequest = new AssumeRoleRequest([
            "roleArn" => $this->roleArn,
            "roleSessionName" => $this->roleSessionName
        ]);
        $runtime = new RuntimeOptions([]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            $result = $this->client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
            if ($result->statusCode != 200) {
                throw new Exception("获取临时token失败");
            }
            return json_decode(json_encode($result->body->credentials), true);
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            throw $error;
        }
    }
}
